package com.xiaoai.redis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaoai.redis.constant.CacheConstant;
import com.xiaoai.redis.entity.SysUser;
import com.xiaoai.redis.mapper.SysUserMapper;
import com.xiaoai.redis.service.SysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * 用户管理实现
 * @author ludangxin
 * @date 2021/8/11
 */
@Slf4j
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = CacheConstant.USER_CACHE_NAME)
public class SysUserServiceImpl implements SysUserService {

   private final SysUserMapper userMapper;

   @Override
   @Cacheable(key = "'" + CacheConstant.USER_CACHE_KEY_PREFIX + "all'", unless = "#result.size() == 0")
   public List<SysUser> queryAll() {
      log.debug("查询全部用户信息～");
      LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
      return userMapper.selectList(queryWrapper);
   }

   
   @Override
   @Cacheable(key = "'" + CacheConstant.USER_CACHE_KEY_PREFIX + "' + #userId", unless = "#result == null")
   public SysUser getUserInfo(Long userId) {
      log.debug("查询用户：{} 详情", userId);
      return userMapper.selectById(userId);
   }

   @Override
   @CacheEvict(key = "'" + CacheConstant.USER_CACHE_KEY_PREFIX + "all'")
   public void add(SysUser user) {
      log.debug("新增用户：{}", user.getName());
      userMapper.insert(user);
   }

   @Override
   @Caching(
       evict = {
           @CacheEvict(key = "'" + CacheConstant.USER_CACHE_KEY_PREFIX + "all'"),
           @CacheEvict(key = "'" + CacheConstant.USER_CACHE_KEY_PREFIX + "' + #userId"
       )
   })
   public void update(Long userId, SysUser user) {
      log.debug("更新用户：{}", user.getName());
      user.setId(userId);
      userMapper.updateById(user);
   }

   @Override
   @Caching(evict = {@CacheEvict(key = "'" + CacheConstant.USER_CACHE_KEY_PREFIX + "all'"),
                     @CacheEvict(key = "'" + CacheConstant.USER_CACHE_KEY_PREFIX + "' + #userId")
   })
   public void delete(Long userId) {
      log.debug("删除用户：{}", userId);
      userMapper.deleteById(userId);
   }
}